package edu.ynu.se.xiecheng.achitectureclass.service;


import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.domain.Result;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.domain.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.domain.vo.LoginVo;
import edu.ynu.se.xiecheng.achitectureclass.utils.CookieUtil;
import edu.ynu.se.xiecheng.achitectureclass.utils.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserService extends LogicService<UserDao, User, Long> {

    @Resource
    private UserDao userdao;
    private final JwtUtil jwtUtil;
    public UserService(UserDao lr, JwtUtil jwtUtil) {
        super(lr);
        this.jwtUtil = jwtUtil;
    }

    public Result login(HttpServletResponse response, String username, String password) {
        User user = userdao.findUserByUsername(username);
        if (user.getPassword().equals(password)) {
            String token = jwtUtil.generateToken(user);
            CookieUtil.setCookies(response, "token", token);
            LoginVo loginVo = new LoginVo(token, user);
            return new Result(true, loginVo, "登录成功！");
        } else {
            // 异常
            return new Result(false, "用户名或密码错误");
        }
    }
}
